package com.hb.config.interceptor;

import com.alibaba.fastjson.JSON;
import com.hb.utils.IpUtils;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.annotation.AfterReturning;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Log4j2
@Component
public class LogInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String ipAddr = IpUtils.getIPAddress(request);
		//记录请求内容
		log.info("---------------------------------------------------");
		log.info("Interface address:\t{}\t\tIP:\t{}", request.getServletPath(), ipAddr);
		log.info("request address:\t{}", request.getRequestURL().toString());
		log.info("request method:\t{}", request.getMethod());
		//获取请求参数(query)
		Enumeration<String> enumeration = request.getParameterNames();
		Map<String, String> parameterMap = new HashMap<>();
		while (enumeration.hasMoreElements()) {
			String parameter = enumeration.nextElement();
			parameterMap.put(parameter, request.getParameter(parameter));
		}
		String str = JSON.toJSONString(parameterMap);
		if (parameterMap.size() > 0) {
			log.info("request Query:\t{}", str);
		}
		return true;

	}



}
